package com.rpc.netty.longConnectinon;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc TextWebSocketFrame表示文本帧
 */
public class  LongConnNettyServerSocketFrameHandler extends
    SimpleChannelInboundHandler<TextWebSocketFrame> {


  //读取消息
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
    System.out.println("服务器端收到消息" + msg.text());

    //回复消息
    ctx.writeAndFlush(new TextWebSocketFrame(
        "服务器端回复的消息" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
  }

  //客户端连接后触发
  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    System.out.println("handlerAdded已调用");
  }

  //客户端断开连接触发
  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    System.out.println("handlerRemoved已调用");

  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
